package org.wevil.service.witcher3;

import org.wevil.entity.witcher3.Witcher3Menu;
import org.wevil.repo.witcher3.Witcher3MenuRepo;
import org.wevil.util.BeanUtil;
import org.wevil.vo.list.MenuListVo;
import org.wevil.vo.node.MenuNodeVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class Witcher3MenuService {

    @Resource
    Witcher3MenuRepo witcher3MenuRepo;

    /** 查询是否有下级菜单 */
    public boolean haveLowerLevel(Integer menuId){
        Integer count = witcher3MenuRepo.countByPid(menuId);
        return count > 0;
    }

    /** 根据菜单id获取菜单列表 */
    public List<MenuListVo> getMenuByIds(List<Integer> menuIds){
        List<Witcher3Menu> sysMenus = witcher3MenuRepo.findByIdIn(menuIds);
        List<MenuListVo> vos = new ArrayList<>();
        sysMenus.forEach(sysMenu -> vos.add(entity2vo(sysMenu)));
        return vos;
    }

    /**
     * 获取当前用户的节点菜单
     * */
    public List<MenuNodeVo> getMenuNode() {
        List<Witcher3Menu> sysMenus = witcher3MenuRepo.findAll();
        List<MenuNodeVo> menuNodeVos = new ArrayList<>();
        sysMenus.forEach(sysMenu -> menuNodeVos.add(entity2NodeVo(sysMenu)));
        return menuNodeVos;
    }

    /**
     * 添加菜单
     * */
    public void addMenu(Witcher3Menu entity) {
        witcher3MenuRepo.save(entity);
    }

    /**
     * 删除菜单
     * */
    public void delMenu(Integer menuId) {
        Optional<Witcher3Menu> optional = witcher3MenuRepo.findById(menuId);
        if(optional.isPresent()){
            witcher3MenuRepo.deleteById(menuId);
        }
    }

    /**
     * 更新菜单
     * */
    public void updateMenu(Witcher3Menu entity) {
        witcher3MenuRepo.update(entity);
    }

    /** 实体转 vo */
    private MenuListVo entity2vo(Witcher3Menu sysMenu) {
        MenuListVo vo = new MenuListVo();
        BeanUtil.copyPropIgnoreNull(sysMenu, vo);
        return vo;
    }

    /**
     * 实体转 Node Vo
     * */
    private MenuNodeVo entity2NodeVo(Witcher3Menu sysMenu){
        MenuNodeVo menuNodeVo = new MenuNodeVo();
        BeanUtil.copyPropIgnoreNull(sysMenu, menuNodeVo);
        return menuNodeVo;
    }

    /** 列表 */
    public List<MenuListVo> list() {
        List<Witcher3Menu> list = witcher3MenuRepo.findAll();
        return getMenuListVos(list);
    }

    /** 获取1级菜单数据 */
    public List<MenuListVo> list1() {
        List<Witcher3Menu> list = witcher3MenuRepo.findByPid(0);
        return getMenuListVos(list);
    }

    /** list 2 vo */
    private List<MenuListVo> getMenuListVos(List<Witcher3Menu> list) {
        List<MenuListVo> vos = new ArrayList<>();
        for(Witcher3Menu menu : list){
            MenuListVo vo = new MenuListVo();
            BeanUtil.copyPropIgnoreNull(menu , vo);
            vos.add(vo);
        }
        return vos;
    }
}
